import numpy as np
import re

def pre_processing(name):
    # 去空格
    name = "".join(name.split())
    name = name.lower()
    name = name.replace('㎎', 'mg')
    name = name.replace('Ⅻ', 'XII')
    name = name.replace('Ⅺ', 'XI')
    name = name.replace('Ⅹ', 'X')
    name = name.replace('Ⅸ', 'IX')
    name = name.replace('Ⅷ', 'VIII')
    name = name.replace('Ⅶ', 'VII')
    name = name.replace('Ⅵ', 'VI')
    name = name.replace('Ⅴ', 'V')
    name = name.replace('Ⅳ', 'IV')
    name = name.replace('Ⅲ', 'III')
    name = name.replace('Ⅱ', 'II')
    name = name.replace('Ⅰ', 'I')
    name = strQ2B(name)
    # 统一转为英文符号
    intab = u"—；。：，【】（）；“”‘’？！｛｝《》／—「」『』〖〗〔〕＊＿＿＋＼〓[]αβγ∽∶‥–‒Ι×"
    outab = u"-;.:,()();\"\"\'\'?!()()/-()()()()*--+/=()aby~::--i*"
    trantab = str.maketrans(intab, outab)  # 一一映射。
    name = name.translate(trantab)  # 返回字符串S的副本，其中每个字符都已通过给定的转换表进行映射。
    # 去特殊符号
    special_char = re.compile("[■□●○◎◇◆△▲＠@!$￥＆&＾^?§№☆★※→←↑↓°;.:,()\"\'?!/*+-=①②•˙∙·®`、]")  #
    name = re.sub(special_char, "", name)
    return name


def strQ2B(ustring):
    """全角转半角"""
    rstring = ""
    for uchar in ustring:
        inside_code = ord(uchar)
        if inside_code == 12288:  # 全角空格直接转换
            inside_code = 32
        elif (65281 <= inside_code <= 65374):  # 全角字符（除空格）根据关系转化
            inside_code -= 65248

        rstring += chr(inside_code)
    return rstring


def bit_product_sum(x, y):
    return sum([item[0] * item[1] for item in zip(x, y)])


def cosine_similarity(x, y, norm=False):
    """ 计算两个向量x和y的余弦相似度 """
    assert len(x) == len(y), "len(x) != len(y)"
    zero_list = [0] * len(x)
    if x == zero_list or y == zero_list:
        return float(1) if x == y else float(0)

    # method 1
    res = np.array([[x[i] * y[i], x[i] * x[i], y[i] * y[i]] for i in range(len(x))])
    cos = sum(res[:, 0]) / (np.sqrt(sum(res[:, 1])) * np.sqrt(sum(res[:, 2])))

    return 0.5 * cos + 0.5 if norm else cos  # 归一化到[0, 1]区间内


def cosine_similarity_main(str1, str2):
    # str1 = pre_processing(str1)
    # str2 = pre_processing(str2)
    A = list(set(str1 + str2))

    # 并集中的每个字符在各自中出现的频率
    d1 = [str1.count(i) for i in A]
    d2 = [str2.count(i) for i in A]
    # print(d1)
    # print(d2)
    cos = cosine_similarity(d1, d2)
    return cos


